package com.xjlsoft.weather.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.xjlsoft.weather.dto.CourseData;

/**
 * @author wangzhi
 */
@RestController
@RequestMapping("/easyExcel")
public class EasyExcelDemo {

    @GetMapping("/writerExcel")
    public void easyExcel(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	//导出文件的名字
        String fileName = "demoExcel";
        //工作簿名称
        String sheetName = "课程价格工作簿";
        //所有行数据，每一行其实就是一个封装的实体对象
        List<CourseData> resultData = getCourseList();
        EasyExcel.write(getOutputStream(fileName,response),CourseData.class).sheet(sheetName).doWrite(resultData);
    }
	
	//给HttpServletResponse设置响应头信息，表示返回的是一个文件流
    public OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            //不同的文件流类型有不同的contentType对照表,可自行百度
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            return response.getOutputStream();
    }

	//模拟业务数据，业务中一般是SQL查询返回的数据
    public static List<CourseData> getCourseList(){
        List<CourseData> courseList = new ArrayList<>();
        courseList.add(new CourseData("语文",10.00));
        courseList.add(new CourseData("数学",10.00));
        courseList.add(new CourseData("英语",10.00));
        return  courseList;
    }

}
